import React, { useState, useEffect } from 'react';
import { Modal, Card, Button, Space, Spin, message, Tag, Divider, Typography } from 'antd';
import { RobotOutlined, CheckCircleOutlined, CloseCircleOutlined, BulbOutlined } from '@ant-design/icons';
import styled from 'styled-components';

const { Text, Paragraph } = Typography;

interface Question {
  id: string;
  question: string;
  type: "single" | "multiple" | "text";
  options?: string[];
  correctAnswer?: string | string[];
  studentAnswer?: string | string[];
  isCorrect?: boolean;
  score?: number;
  fullScore?: number;
  explanation?: string;
}

interface Homework {
  id: string;
  title: string;
  course: string;
  teacher: string;
  description: string;
  deadline: string;
  status: "未提交" | "已提交" | "已批改" | "已过期";
  type: "file" | "quiz";
  score?: number;
  fullScore?: number;
  submittedAt?: string;
  gradedAt?: string;
  feedback?: string;
  attachments?: string[];
  submittedFiles?: string[];
  questions?: Question[];
  hasAIExplanation?: boolean;
}

interface AIExplanationModalProps {
  visible: boolean;
  homework: Homework | null;
  onCancel: () => void;
}

const StyledModal = styled(Modal)`
  .ant-modal-content {
    max-height: 80vh;
    overflow-y: auto;
  }
`;

const QuestionCard = styled(Card)`
  margin-bottom: 16px;
  border: 1px solid #d9d9d9;
  
  .ant-card-head {
    background-color: #fafafa;
    border-bottom: 1px solid #d9d9d9;
  }
`;

const AnswerSection = styled.div`
  margin: 12px 0;
  padding: 12px;
  border-radius: 6px;
  background-color: #f8f9fa;
`;

const CorrectAnswer = styled.div`
  color: #52c41a;
  font-weight: bold;
`;

const WrongAnswer = styled.div`
  color: #ff4d4f;
  font-weight: bold;
`;

const AIExplanationSection = styled.div`
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
`;

const AIExplanationModal: React.FC<AIExplanationModalProps> = ({
  visible,
  homework,
  onCancel
}) => {
  const [loading, setLoading] = useState(false);
  const [aiExplanations, setAiExplanations] = useState<Record<string, string>>({});

  useEffect(() => {
    if (visible && homework && !homework.hasAIExplanation) {
      generateAIExplanations();
    }
  }, [visible, homework]);

  const generateAIExplanations = async () => {
    if (!homework?.questions) return;

    setLoading(true);
    try {
      // 模拟AI解析生成
      const explanations: Record<string, string> = {};
      
      for (const question of homework.questions) {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        let explanation = '';
        
        if (question.type === 'single') {
          if (question.isCorrect) {
            explanation = `✅ 回答正确！您选择了"${question.studentAnswer}"，这是正确答案。\n\n💡 解析：${question.explanation || '这道题目考察了基础概念的理解，您的答案完全正确。'}`;
          } else {
            explanation = `❌ 回答错误。您选择了"${question.studentAnswer}"，但正确答案是"${question.correctAnswer}"。\n\n💡 解析：${question.explanation || '这道题目需要仔细分析每个选项的含义，建议您重新理解相关概念。'}\n\n🔍 学习建议：建议您复习相关知识点，加深对概念的理解。`;
          }
        } else if (question.type === 'multiple') {
          const studentAnswers = Array.isArray(question.studentAnswer) ? question.studentAnswer : [];
          const correctAnswers = Array.isArray(question.correctAnswer) ? question.correctAnswer : [];
          
          if (question.isCorrect) {
            explanation = `✅ 回答正确！您选择了${studentAnswers.join('、')}，这些都是正确答案。\n\n💡 解析：${question.explanation || '这道多选题考察了多个相关概念，您的选择完全正确。'}`;
          } else {
            const missing = correctAnswers.filter(a => !studentAnswers.includes(a));
            const extra = studentAnswers.filter(a => !correctAnswers.includes(a));
            
            explanation = `❌ 回答部分错误。\n\n您的选择：${studentAnswers.join('、')}\n正确答案：${correctAnswers.join('、')}`;
            
            if (missing.length > 0) {
              explanation += `\n\n❌ 缺少：${missing.join('、')}`;
            }
            if (extra.length > 0) {
              explanation += `\n\n❌ 多余：${extra.join('、')}`;
            }
            
            explanation += `\n\n💡 解析：${question.explanation || '这道多选题需要全面考虑所有正确选项，建议您仔细分析每个选项。'}`;
          }
        } else if (question.type === 'text') {
          if (question.isCorrect) {
            explanation = `✅ 回答正确！您的答案：${question.studentAnswer}\n\n💡 解析：${question.explanation || '您的回答准确完整，体现了对知识点的深入理解。'}`;
          } else {
            explanation = `❌ 回答需要改进。\n\n您的答案：${question.studentAnswer}\n参考答案：${question.correctAnswer}\n\n💡 解析：${question.explanation || '建议您重新理解相关概念，补充遗漏的知识点。'}\n\n🔍 学习建议：可以查阅相关教材或资料，加深对知识点的理解。`;
          }
        }
        
        explanations[question.id] = explanation;
      }
      
      setAiExplanations(explanations);
      message.success('AI解析生成完成！');
    } catch (error) {
      message.error('AI解析生成失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const getScoreColor = (score: number, fullScore: number) => {
    const percentage = (score / fullScore) * 100;
    if (percentage >= 90) return '#52c41a';
    if (percentage >= 80) return '#1890ff';
    if (percentage >= 60) return '#faad14';
    return '#ff4d4f';
  };

  const getScoreText = (score: number, fullScore: number) => {
    const percentage = (score / fullScore) * 100;
    if (percentage >= 90) return '优秀';
    if (percentage >= 80) return '良好';
    if (percentage >= 60) return '及格';
    return '不及格';
  };

  if (!homework || !homework.questions) {
    return null;
  }

  return (
    <StyledModal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <RobotOutlined style={{ color: '#1890ff' }} />
          <span>AI智能解析 - {homework.title}</span>
        </div>
      }
      visible={visible}
      onCancel={onCancel}
      width={900}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>
      ]}
    >
      <div style={{ marginBottom: 16 }}>
        <Card size="small">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <Text strong>总分：</Text>
              <Text style={{ color: getScoreColor(homework.score || 0, homework.fullScore || 100) }}>
                {homework.score}/{homework.fullScore}
              </Text>
            </div>
            <Tag color={getScoreColor(homework.score || 0, homework.fullScore || 100)}>
              {getScoreText(homework.score || 0, homework.fullScore || 100)}
            </Tag>
          </div>
        </Card>
      </div>

      {loading && (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>
            <Text>AI正在分析您的答题情况...</Text>
          </div>
        </div>
      )}

      {!loading && homework.questions.map((question, index) => (
        <QuestionCard
          key={question.id}
          title={`第 ${index + 1} 题`}
          extra={
            <Space>
              <span style={{ color: question.type === 'single' ? '#1890ff' : question.type === 'multiple' ? '#52c41a' : '#fa8c16' }}>
                {question.type === 'single' ? '单选题' : question.type === 'multiple' ? '多选题' : '问答题'}
              </span>
              <Tag color={question.isCorrect ? 'success' : 'error'}>
                {question.score}/{question.fullScore}
              </Tag>
            </Space>
          }
        >
          <div style={{ marginBottom: 16 }}>
            <h4>{question.question}</h4>
          </div>

          {question.options && (
            <div style={{ marginBottom: 16 }}>
              <Text strong>选项：</Text>
              <div style={{ marginTop: 8 }}>
                {question.options.map((option, optIndex) => (
                  <div key={optIndex} style={{ margin: '4px 0' }}>
                    <Text style={{ 
                      color: Array.isArray(question.correctAnswer) 
                        ? question.correctAnswer.includes(option) ? '#52c41a' : '#666'
                        : question.correctAnswer === option ? '#52c41a' : '#666'
                    }}>
                      {option}
                    </Text>
                  </div>
                ))}
              </div>
            </div>
          )}

          <AnswerSection>
            <div style={{ marginBottom: 8 }}>
              <Text strong>您的答案：</Text>
              {question.isCorrect ? (
                <CorrectAnswer>
                  {Array.isArray(question.studentAnswer) 
                    ? question.studentAnswer.join('、') 
                    : question.studentAnswer}
                  <CheckCircleOutlined style={{ marginLeft: 8 }} />
                </CorrectAnswer>
              ) : (
                <WrongAnswer>
                  {Array.isArray(question.studentAnswer) 
                    ? question.studentAnswer.join('、') 
                    : question.studentAnswer}
                  <CloseCircleOutlined style={{ marginLeft: 8 }} />
                </WrongAnswer>
              )}
            </div>
            
            {!question.isCorrect && (
              <div>
                <Text strong>正确答案：</Text>
                <CorrectAnswer>
                  {Array.isArray(question.correctAnswer) 
                    ? question.correctAnswer.join('、') 
                    : question.correctAnswer}
                </CorrectAnswer>
              </div>
            )}
          </AnswerSection>

          {aiExplanations[question.id] && (
            <AIExplanationSection>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                <BulbOutlined style={{ marginRight: 8 }} />
                <Text strong style={{ color: 'white' }}>AI智能解析</Text>
              </div>
              <Paragraph style={{ color: 'white', margin: 0 }}>
                {aiExplanations[question.id].split('\n').map((line, lineIndex) => (
                  <div key={lineIndex} style={{ marginBottom: line ? '8px' : '4px' }}>
                    {line}
                  </div>
                ))}
              </Paragraph>
            </AIExplanationSection>
          )}
        </QuestionCard>
      ))}

      {!loading && Object.keys(aiExplanations).length === 0 && homework.hasAIExplanation && (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Text type="secondary">暂无AI解析数据</Text>
        </div>
      )}
    </StyledModal>
  );
};

export default AIExplanationModal; 